package com.xkl.springdoc.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.date.DateUtil;
import com.xkl.springdoc.common.R;
import com.xkl.springdoc.domain.SaleList;
import com.xkl.springdoc.domain.User;
import com.xkl.springdoc.request.SaleListDTO;
import com.xkl.springdoc.request.UserDTO;
import com.xkl.springdoc.response.SaleListVo;
import com.xkl.springdoc.response.UserVo;
import com.xkl.springdoc.service.ISaleListService;
import com.xkl.springdoc.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 订单管理
 *
 * @version: 1.0.0-SNAPSHOT
 * @author: 码农小卡拉
 * @createTime: 2025-09-17 11:22
 **/
@Slf4j
@Service
public class SaleListServiceImpl implements ISaleListService {

    private static List<SaleList> saleListList = new ArrayList<SaleList>();

    @Override
    public R addSaleList(SaleListDTO saleListDTO) {
        log.info("新增订单: {}", saleListDTO);
        boolean exists = saleListList.stream().anyMatch(saleList -> saleList.getId().equals(saleListDTO.getId()));
        if (exists) {
            log.error("订单已存在");
            return R.fail("订单已存在");
        }
        SaleList saleList = new SaleList();
        BeanUtil.copyProperties(saleListDTO, saleList);
        saleList.setCreateTime(DateUtil.date());
        saleListList.add(saleList);
        return R.ok();
    }

    @Override
    public R editSaleList(SaleListDTO saleListDTO) {
        log.info("更新订单: {}", saleListDTO);
        boolean exists = saleListList.stream().anyMatch(saleList -> saleList.getId().equals(saleListDTO.getId()));
        if (!exists) {
            log.error("订单不存在");
            return R.fail("订单不存在");
        }
        saleListList.stream().filter(v -> v.getId().equals(saleListDTO.getId())).findFirst().ifPresent(saleList -> BeanUtil.copyProperties(saleListDTO, saleList, CopyOptions.create().setIgnoreNullValue(true)));
        return R.ok();
    }

    @Override
    public R deleteSaleList(Long id) {
        return R.ok(saleListList.removeIf(saleList -> saleList.getId().equals(id)));
    }

    @Override
    public R getSaleList(Long id) {
        SaleList saleList = saleListList.stream().filter(v -> v.getId().equals(id)).findFirst().orElse(null);
        if (null == saleList) {
            log.error("订单不存在");
            return R.fail("订单不存在");
        }
        SaleListVo vo = new SaleListVo();
        BeanUtil.copyProperties(saleList, vo);
        return R.ok(vo);
    }

    @Override
    public R<List<SaleListVo>> getSaleLists() {
        List<SaleListVo> list = saleListList.stream().map(saleList -> {
            SaleListVo vo = new SaleListVo();
            BeanUtil.copyProperties(saleList, vo);
            return vo;
        }).toList();
        return R.ok(list);
    }
}
